import { computed, ref, unref, watch } from 'vue'
import { deepClone } from 'utils/index'

export function useColumns(propsRef) {
  const columnsRef = ref(unref(propsRef).columns)

  const getColumnsRef = computed(() => {
    const columns = deepClone(unref(columnsRef))
    if (!columns) {
      return []
    }
    return columns
  })
  const getViewColumns = computed(() => {
    const viewColumns = sortFixedColumn(unref(getColumnsRef))
    const columns = deepClone(viewColumns)
    return columns
  })
  watch(
    () => unref(propsRef).columns,
    (columns) => {
      columnsRef.value = columns
    }
  )
  function sortFixedColumn(columns) {
    const fixedLeftColumns = []
    const fixedRightColumns = []
    const defColumns = []
    for (const column of columns) {
      if (column.fixed === 'left') {
        fixedLeftColumns.push(column)
        continue
      }
      if (column.fixed === 'right') {
        fixedRightColumns.push(column)
        continue
      }
      defColumns.push(column)
    }
    return [...fixedLeftColumns, ...defColumns, ...fixedRightColumns].filter((item) => !item.defaultHidden)
  }
  return {
    getColumnsRef,
    getViewColumns
  }
}
